package singleton;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 测试反射和反序列化破解单例模式
 * 
 * @author beeworkshop
 *
 */
public class Test2 {

	public static void main(String[] args) throws Exception {
		SingletonDemo s1 = SingletonDemo.getInstance();
		SingletonDemo s2 = SingletonDemo.getInstance();

		System.out.println(s1);
		System.out.println(s2);

		// 通过反射的方式直接调用私有构造器
//		Class<SingletonDemo> clazz = (Class<SingletonDemo>) Class.forName("singleton.SingletonDemo");
//		Constructor<SingletonDemo> c = clazz.getDeclaredConstructor(null);
//		c.setAccessible(true);
//		SingletonDemo  s3 = c.newInstance();
//		SingletonDemo  s4 = c.newInstance();
//		System.out.println(s3);
//		System.out.println(s4);

/*
可以通过抛出异常的方式来阻止通过反射的方式直接调用私有构造器
    private SingletonDemo() { //构造器
        if(instance!=null) throw new RuntimeException("不能绕过！");
    }
*/

		// 通过反序列化的方式构造多个对象
		FileOutputStream fos = new FileOutputStream("d:/a.txt");
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		oos.writeObject(s1);
		oos.close();
		fos.close();

		ObjectInputStream ois = new ObjectInputStream(new FileInputStream("d:/a.txt"));
		SingletonDemo s3 = (SingletonDemo) ois.readObject();
		System.out.println(s3);

	}
}